package com.talent.jiwen.home;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.talent.jiwen.R;
import com.talent.jiwen.base.BaseActivity;
import com.talent.jiwen.http.common.ActivityLifeCycleEvent;
import com.talent.jiwen.http.common.ApiFactory;
import com.talent.jiwen.http.common.HttpUtil;
import com.talent.jiwen.http.common.ProgressSubscriber;
import com.talent.jiwen.http.result.ApplyTeacherResult;
import com.talent.jiwen.http.result.GroupInfoResult;
import com.talent.jiwen.teacher.TeacherDetailActivity;
import com.talent.jiwen.util.ImageUtil;
import com.talent.jiwen.util.SPConstant;
import com.talent.jiwen.util.SPUtil;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.ButterKnife;
import rx.Observable;

public class SendOrderActivity extends BaseActivity {
    @BindView(R.id.waitTv)
    TextView waitTv;
    @BindView(R.id.waitTimeTv)
    TextView waitTimeTv;
    @BindView(R.id.lookingTeacherIv)
    ImageView lookingTeacherIv;
    @BindView(R.id.receivedTeacherTv)
    TextView receivedTeacherTv;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;

    private List<ApplyTeacherResult.ApplyTeacherInfo> dataList = new ArrayList<>();

    public static final String PARAM_ORDER_ID = "param.order.id";
    private String orderId;

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_send_order;
    }

    @Override
    public String titleName() {
        return getString(R.string.send_order);
    }

    @Override
    protected void initData() {

        final long startTime = new Date().getTime();

        final Handler startTimehandler = new Handler(){
            public void handleMessage(android.os.Message msg) {
                if (null != waitTimeTv) {
                    waitTimeTv.setText((String) msg.obj);
                }
            }
        };
        new Timer("计时器").scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                int time = (int)((new Date().getTime() - startTime) / 1000);
                String timeFormat;
                String min = new DecimalFormat("00").format(time / 60);
                if (Integer.parseInt(min) < 60){
                    String mm = new DecimalFormat("00").format(time / 60);
                    String ss = new DecimalFormat("00").format(time % 60);
                    timeFormat = new String( mm + ":" + ss);
                }else{
                    String hh = new DecimalFormat("00").format(time / 3600);
                    String mm = new DecimalFormat("00").format(time % 3600 / 60);
                    String ss = new DecimalFormat("00").format(time % 60);
                    timeFormat = new String( hh + ":" + mm + ":" + ss);
                }
                Message msg = new Message();
                msg.obj = timeFormat;
                startTimehandler.sendMessage(msg);
            }

        }, 0, 1000L);

        ImageUtil.loadCircleImage(this , R.mipmap.iv_teacher_test , lookingTeacherIv);

        receivedTeacherTv.setVisibility(View.VISIBLE);

        orderId = getIntent().getStringExtra(PARAM_ORDER_ID);

        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setAdapter(new CommonAdapter<ApplyTeacherResult.ApplyTeacherInfo>(SendOrderActivity.this , R.layout.item_order_teacher , dataList){
            @Override
            protected void convert(ViewHolder holder, final ApplyTeacherResult.ApplyTeacherInfo data, int position) {
                ImageView teacherIv = holder.getView(R.id.teacherIv);
                TextView nameTv = holder.getView(R.id.nameTv);
                TextView desTv = holder.getView(R.id.desTv);
                TextView priceTv = holder.getView(R.id.priceTv);
                TextView optionTv = holder.getView(R.id.optionTv);

                ImageUtil.loadCorner4Image(SendOrderActivity.this , data.getTeacherHeadImage() , teacherIv);
                nameTv.setText(data.getTeacherName());
                desTv.setText("评分 " + data.getEffectScore() + "    解决次数  " + data.getSolveCount());

                optionTv.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        acceptTeacher(data.getTeacherId());
                    }
                });
                holder.itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        TeacherDetailActivity.startTeacherDetailActivity(SendOrderActivity.this, TeacherDetailActivity.TYPE_ACCEPT_COURSE , data.getTeacherId() , orderId);
                    }
                });
            }
        });

        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                getApplyTeacherList();
            }
        });
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshlayout) {
                refreshLayout.finishLoadMoreWithNoMoreData();
            }
        });

        refreshLayout.autoRefresh();
    }


    /**获取教师申请列表
     *
     */
    private void getApplyTeacherList(){
        Map<String, String> map = new HashMap<>();
        map.put("studentId" , SPUtil.stringOut(SPConstant.USER_ID));
        map.put("orderId" , orderId);

        Observable observable = ApiFactory.getEducationApiSingleton().getApplyTeacherList(SPUtil.stringOut(SPConstant.TOKEN) , map);
        HttpUtil.getInstance().toSubscribe(observable, new ProgressSubscriber<ApplyTeacherResult>(SendOrderActivity.this) {
            @Override
            protected void _onNext(ApplyTeacherResult applyTeacherResult) {
                dataList.clear();
                dataList.addAll(applyTeacherResult.getApplyList());

                recyclerView.getAdapter().notifyDataSetChanged();

                refreshLayout.finishRefresh();
            }

            @Override
            protected void _onError(String message) {
                showToast(message);
            }
        }, ActivityLifeCycleEvent.DESTROY, lifecycleSubject,false);
    }

    /**接受教师
     *
     * @param teacherId
     */
    private void acceptTeacher(String teacherId){
        Map<String, String> map = new HashMap<>();
        map.put("teacherId" , teacherId);
        map.put("orderId" , orderId);

        Observable observable = ApiFactory.getEducationApiSingleton().acceptTeacher(SPUtil.stringOut(SPConstant.TOKEN) , map);
        HttpUtil.getInstance().toSubscribe(observable, new ProgressSubscriber<Void>(SendOrderActivity.this) {
            @Override
            protected void _onNext(Void v) {
                finish();
            }

            @Override
            protected void _onError(String message) {
                showToast(message);
            }
        }, ActivityLifeCycleEvent.DESTROY, lifecycleSubject,true);
    }

    /**启动该页面
     *
     * @param context
     * @param orderId
     */
    public static void startSendOrderActivity(Context context , String orderId){
        Intent intent = new Intent();
        intent.setClass(context , SendOrderActivity.class);
        intent.putExtra(PARAM_ORDER_ID , orderId);
        context.startActivity(intent);

    }
}
